<template>
    <div class="app-container" style="min-height:750px">

        <el-row>
            <el-form :model="pictureForm" ref="pictureForm" size="small" :inline="true" label-width="78px">
                <el-form-item label="顾客信息" prop="visitNum">
                    <el-select v-model="pictureForm.visitNum" placeholder="顾客信息" style="width: 450px" clearable
                        @change="search">
                        <el-option v-for="item in baseInfoData" :key="item.visitId"
                            :label="'顾客编号：' + item.visitNum + ' 状态：' + getDiagnosisStatusLabel(item.status) + ' 诊断：' + item.doctorDiagnosis"
                            :value="item.visitNum"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="拍照设备" prop="type">
                    <el-select v-model="pictureForm.type" placeholder="拍照设备" style="width: 120px" clearable
                        @change="search">
                        <el-option v-for="dict in dicts.photo_upload_type" :key="dict.dictValue"
                                   :label="dict.dictLabel" :value="dict.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="采集日期">
                    <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                        @change="search"></el-date-picker>
                </el-form-item>
                <el-button type="primary" size="mini" @click="search">查询</el-button>
                <el-button type="primary" size="mini" @click="comparePics">对比显示该顾客照片</el-button>
            </el-form>
        </el-row>
        <div v-if="!comparePicsDialogVisible">
            <el-row v-for="(item, index) in picData" :key="index" style="margin-top:15px;">
                <el-col :span="24" class="group-info">
                    <span> 顾客编号:{{ item.sysPatientPhotos[0].visitNum }}</span>
                    <span> 采集日期:{{ item.sysPatientPhotos[0].createTime }}</span>
                    <span class="device">采集时刻:<dict-tag :options="dicts.sys_diagnosis_status"
                            :value="item.sysPatientPhotos[0].status" /></span>
                    <span class="device">设备:<dict-tag :options="dicts.photo_upload_type"
                            :value="item.sysPatientPhotos[0].type" /></span>
                    <span>上传人:{{ item.sysPatientPhotos[0].nickName }}</span>
                    <span v-if="item.scoreAiAll" style="color: #1890ff">Ai mMASI总分:{{ (item.scoreAiAll).toFixed(1)
                    }}分</span>
                    <el-button size="mini" type="primary" icon="el-icon-delete" @click="delPics(item.p_index)"
                        v-show="index === 0 || userName === 'admin'" style="float: right;">删除</el-button>
                    <el-button size="mini" type="primary" @click="startHhbAi(item, index)"
                        style="float: right;">启动黄褐斑Ai</el-button>
                </el-col>
                <el-col :span="24" style="display:flex;flex-wrap: wrap;">
                    <div class="img-txt" v-loading="loadingIndex == item.p_index" element-loading-text="Ai分析中"
                        v-for="(it, Mindex) in item.sysPatientPhotos" :key="Mindex">
                        <div class="user-info-myImg">
                            <myImg style="width: 260px" :src="it.thumbnail" :preview-src-list="srcList"
                                   :fileSizeList="fileSizeListData" :myImgIndex="Mindex" @click="getPicPreviewList(item)">
                            </myImg>
                        </div>

<!--                        <div class="user-info-head">-->
<!--                            <el-image class="img-style" fit="contain" :src="it.thumbnail"-->
<!--                                @click="watchBigPic(item,Mindex)" :preview-src-list="srcList"></el-image>-->
<!--                        </div>-->
                        <span>
                            <dict-tag :options="dicts.photo_lighting_type" :value="it.faceLight" />
                            <dict-tag :options="dicts.sys_diagnosis_status" :value="it.status" />
                            <dict-tag :options="dicts.sys_face_part" :value="it.facePart" />
                            <div>{{ (it.fileSize / 1024 / 1024).toFixed(2) }}M(压缩质量:{{ it.compressionRatio }})</div>
                            <div v-if="it.scoreAi != null" style="color: #1890ff">Ai mMASI评分:{{ (it.scoreAi).toFixed(1) }}分</div>

                        </span>
                    </div>
                </el-col>
            </el-row>
        </div>
        <el-dialog title="照片比对" :visible.sync="comparePicsDialogVisible" width="85%" center :close-on-click-modal="false"
            :append-to-body="true" >
            <comparePics :patientId="patientId" v-if="comparePicsDialogVisible"></comparePics>
        </el-dialog>
<!--        <el-dialog title="照片标注" :visible.sync="picMarkDialogVisible" width="100%" center :close-on-click-modal="false"-->
<!--            :append-to-body="true" v-dialogDrag>-->
<!--            <PhotoMark :currentUrl="currentUrl" :imgList="imgList" :myImgIndex="myImgIndex" v-if="picMarkDialogVisible">-->
<!--            </PhotoMark>-->
<!--        </el-dialog>-->
    </div>
</template>

<script>
import {getDict} from "@/api/dict";

import { listPhoto,delPhotoByGroup, startAi,getVisit } from "@/api/morePics";
import comparePics from "@/components/LandingPage/comparePics";
import myImg from "@/components/LandingPage/myImg/myMainImg"
// import PhotoMark from "@/views/components/photoMark/photoMark.vue";
export default {
    name: "morePics",
    components: { comparePics,myImg  },
    props: {
        patientId: {
            type: Number,
            default: null,
        },
        timer: {
            type: Number,
            default: null,
        },
        userName: {
            type: String,
            default: null,
        }
    },
    data() {
        return {
            dicts: {
                sys_diagnosis_status: [],
                photo_upload_type: [],
                photo_lighting_type:[],
                sys_face_part:[],
            },
            loadingIndex: '',
            cycleTimer: null,
            picData: [],
            dateRange: [],
            srcList: [],
            fileSizeListData: [],
            pictureForm: {
                photoLightingType: '',
                type: '',
                visitNum: '',
                patientId: ''
            },
            comparePicsDialogVisible: false,
            picMarkDialogVisible: false,
            currentUrl: '',
            imgList: [],
            myImgIndex: '',//picData 第几组的index下 第几个照片的index
            baseInfoData: [],

        };
    },
    async created() {
        await this.init()

        this.getPatientList();
        this.search();
    },
    watch: {
        timer: function () {
            this.pictureForm.patientId = this.patientId
            // this.pictureForm.visitNum = this.visitNum
            this.getPatientList();
            this.search();
        },
    },
    methods: {
        async init() {
            for (const item in Object.entries(this.dicts)) {
                const key = Object.entries(this.dicts)[item][0]
                await this.getDict(key);
            }
        },
        // 获取字典项
        async getDict(params) {
            const {code, data} = await getDict(params)
            if (code === 200) {
                this.dicts[params] = data || []
            }
        },
        //获取诊断状态字典值对应的label
        getDiagnosisStatusLabel(status) {
            let label = ''
            // console.log('getDiagnosisStatusLabel',this.dicts)
            this.dicts.sys_diagnosis_status.forEach((item) => {
                if (item.dictValue == status) {
                    label = item.dictLabel
                }
            })
            return label

        },
        /** id转化成对应的文字 */
        matchDict: function (key, id) {
            let _this = this;
            const result = _this.dicts[key];
            // console.log('matchDict',result)
            let textValue = "";
            result.forEach((item) => {
                if (item.dictValue == id) {
                    textValue = item.dictLabel;
                }
            });
            return textValue;
        },
        // 获取顾客登记列表
        getPatientList() {
            const queryParams = { pageNum: 1, pageSize: 9999, patientId: this.patientId }
            getVisit(queryParams).then(
                (response) => {
                    this.baseInfoData = response.rows
                    this.baseInfoData.forEach(item => {
                        item.doctorDiagnosis = item.doctorDiagnosis.replace(/ *\([^)]*\) */g, "")
                    })
                    // this.baseInfoData.forEach(item => {
                    //     item.area = [
                    //         Number(item.provinceId),
                    //         Number(item.cityId),
                    //         Number(item.countyId),
                    //     ];
                    // })
                }
            )
        },

        comparePics() { this.comparePicsDialogVisible = true },
        //查询
        search() {
            this.pictureForm.patientId = this.patientId
            this.getPhotoList()
        },
        //根据病人id获取图片列表
        getPhotoList(index) {
            listPhoto(this.addDateRange(this.pictureForm, this.dateRange)).then((res) => {
                if(res.code!==200){
                    return
                }
                let that = this
                if (res.data.length > 0) {
                    this.picData = res.data;

                    this.picData.forEach((item, indexs) => {
                        item.scoreAiAll = 0
                        item.sysPatientPhotos.forEach(it => {
                            if (it.score && JSON.parse(it.score).left) {
                                it.scoreAi = 0.3 * JSON.parse(it.score).left.area * JSON.parse(it.score).left.color
                                if (indexs === index) {
                                    this.loadingIndex = ''
                                    this.$message.success("Ai分析成功");
                                    clearInterval(that.cycleTimer);
                                }

                            }
                            if (it.score && JSON.parse(it.score).brow) {
                                it.scoreAi = 0.3 * JSON.parse(it.score).brow.area * JSON.parse(it.score).brow.color + 0.1 * JSON.parse(it.score).chin.area * JSON.parse(it.score).chin.color
                                if (indexs === index) {
                                    this.loadingIndex = ''
                                    // this.$message.success("Ai分析成功");
                                    clearInterval(that.cycleTimer);
                                }

                            }
                            if (it.score && JSON.parse(it.score).right) {
                                it.scoreAi = 0.3 * JSON.parse(it.score).right.area * JSON.parse(it.score).right.color
                                if (indexs === index) {
                                    this.loadingIndex = ''
                                    // this.$message.success("Ai分析成功");
                                    clearInterval(that.cycleTimer);
                                }

                            }
                            if (it.scoreAi != null) {
                                item.scoreAiAll += it.scoreAi
                            }
                            it.patientName = item.patientName
                            it.age = item.age
                            it.doctorDiagnosis = item.doctorDiagnosis.replace(/ *\([^)]*\) */g, "")
                            // it.points = this.formatPoints(it.points)
                            // it.sysPhotoMarks = this.formatSysPhotoMarks(it.sysPhotoMarks)
                        })
                    })
                    console.log('this.picData', this.picData)
                } else {
                    this.picData = [];
                }
            });
        },
        // //格式化画图组件点位格式数据
        // formatPoints(data) {
        //     if (data != null) {
        //         let mData = []
        //         // console.log(JSON.parse(data))
        //         JSON.parse(data).forEach((item, index) => {
        //             let itPoint = []
        //             item.forEach((it, mindex) => {
        //                 itPoint.push({ x: it[0], y: it[1] })
        //                 if (item.length - 1 === mindex) {
        //                     //最后一个点连接到第一个点形成闭合
        //                     itPoint.push({ x: item[0][0], y: item[0][1] })
        //                 }
        //             })
        //             mData.push({ points: itPoint, type: 'route' })
        //         })
        //         // console.log(mData)
        //         return mData
        //     } else {
        //         return null
        //     }
        // },
        // // 格式化画图组件人工标注点位格式数据
        // formatSysPhotoMarks(data) {
        //     return data.map((item) => { return { ...item, points: JSON.parse(item.points), type: 'route' } })
        // },
        getPicPreviewList(row) {
            console.log('getPicPreviewList',row)
            this.srcList = []
            this.fileSizeListData = []
            row.sysPatientPhotos.forEach((it) => {
                this.srcList.push(it.photoAddress)
                // this.fileSizeListData.push(`<div>姓名:${it.patientName}</div><div>年龄:${it.age}</div><div >医生诊断:${it.doctorDiagnosis}</div><div>采集状态:${this.matchDict('sys_diagnosis_status', it.status)}</div><div>采集设备:${this.matchDict('photo_upload_type', it.type)}</div><div>采集日期:${it.createTime}</div><div>采集人:${it.nickName}</div><div >${it.scoreAi ? 'Ai mMASI评分:' + it.scoreAi + '分' : ''} </div ><div style='margin-top:20px'>光照类型:${this.matchDict('photo_lighting_type', it.faceLight)}</div><div>部位:${this.matchDict('sys_face_part', it.facePart)}</div><div>文件大小:${(it.fileSize / 1024 / 1024).toFixed(2)}M</div><div>压缩比:${it.compressionRatio}</div>`)

            })
        },
        watchBigPic(row, Mindex) {
            this.myImgIndex = Mindex
            this.currentUrl = row.sysPatientPhotos[Mindex].photoAddress
            row.sysPatientPhotos.forEach(item => {
                item.patientName = row.patientName
                item.age = row.age
                item.doctorDiagnosis = row.doctorDiagnosis.replace(/ *\([^)]*\) */g, "")
            })
            this.imgList = row.sysPatientPhotos
            console.log('this.imgList',this.imgList)
            // this.picMarkDialogVisible = true
        },
        //启动黄褐斑AI
        startHhbAi(item, index) {
            let that = this
            if (this.loadingIndex) {
                this.$confirm('已有照片正在评分,请稍后再试!', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {

                }).catch(() => {

                });
                return
            }
            if (item.scoreAiAll) {
                this.$confirm('已有Ai mMASI评分,请确定是否进行重新评分?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    if (that.cycleTimer) {
                        // clearInterval(that.cycleTimer);
                    }
                    this.startHhbAiAgain(item, index)
                }).catch(() => {
                    return
                });
            } else {
                this.startHhbAiAgain(item, index)
            }
        },
        startHhbAiAgain(item, index) {
            let photoIds = []
            let comparePhotoIds = []
            let photoItem1 = item.sysPatientPhotos.find(it => {
                return it.faceLight == '1' && it.facePart == '0'
            })
            let photoItem2 = item.sysPatientPhotos.find(it => {
                return it.faceLight == '1' && it.facePart == '1'
            })
            let photoItem3 = item.sysPatientPhotos.find(it => {
                return it.faceLight == '1' && it.facePart == '2'
            })
            item.sysPatientPhotos.forEach(it => {
                if (it.faceLight == '1' && it.facePart == '0') {
                    comparePhotoIds.push(it.photoId)
                }
                if (it.faceLight == '1' && it.facePart == '1') {
                    comparePhotoIds.push(it.photoId)
                }
                if (it.faceLight == '1' && it.facePart == '2') {
                    comparePhotoIds.push(it.photoId)
                }
            })
            if (photoItem1 && photoItem2 && photoItem3 && comparePhotoIds.length == 3) {
                photoIds.push(photoItem1.photoId)
                photoIds.push(photoItem2.photoId)
                photoIds.push(photoItem3.photoId)
                photoIds = photoIds.join(',')
                console.log('photoIds---', photoIds)
                startAi({ photoIds: photoIds, type: '0' }).then(response => {
                    if (response.code == 200) {
                        let that = this
                        that.loadingIndex = item.p_index
                        if (item.scoreAiAll) {
                            setTimeout(function () {
                                that.getPhotoList(index)
                            }, 9000)
                        } else {
                            that.cycleTimer = setInterval(function () {
                                console.log("每隔3s执行一次");
                                that.getPhotoList(index)
                            }, 3000);
                        }




                    }
                })
            } else {
                this.$confirm(`无法进行Ai分析,Ai分析需光照类型为<strong>Standard</strong>,且脸部部位为<strong>左面部, 正面部, 右面部</strong>有且有三张!`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    dangerouslyUseHTMLString: true,
                }).then(() => {
                    return
                }).catch(() => {
                    return
                });
            }

        },


        delPics(pIndex) {
            const that = this
            that.$prompt('请输入删除照片原因', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(({ value }) => {
                delPhotoByGroup(pIndex).then((res) => {
                    that.picData = that.picData.filter((item) => item.p_index != pIndex)
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });

                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消输入'
                });
            });
        },

    },
};
</script>
<style scoped rel="stylesheet/scss"  lang="scss">
//::v-deep .el-dialog {
//    margin-top: 0 !important;
//}
//
//::v-deep .el-dialog:not(.is-fullscreen) {
//    margin-top: 0 !important;
//}

.img-txt {
    display: flex;
    flex-direction: column;
    text-align: center;
    margin: 14px;
    .user-info-myImg{
        width: 260px;
        height: 412px;
        display: flex;
        align-items: center;
    }

    .user-info-head {
        width: 260px;
        height: 412px;

        //border: 1px solid #000;
        .img-style {
            width: 100%;
            height: 100%;

            ::v-deep .el-image__error {
                opacity: 0;
            }
        }
    }
}

.group-info {
    display: flex;
}

.group-info span {
    margin-right: 15px;
}

.group-info .device div {
    display: inline-block;
    vertical-align: top;
}
</style>
